/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 *
 */

import { FileSet, hvigorCore } from '@ohos/hvigor';
import path from 'path';

import { BuildArtifactExtension } from '../../const/build-directory-const.js';
import { FileUtil } from '../../utils/file-util.js';
import { BaseSign } from '../base/base-sign.js';
import { TaskNames } from '../common/task-names.js';
import { TargetTaskService } from '../service/target-task-service.js';
import { SignModel } from '../sign/command-builder-impl/sign-model.js';

import { PackageHsp } from './package-hsp.js';
import { CommonConst } from '../../const/common-const.js';

/**
 * Sign hsp
 *
 * @since 2023/1/17
 */
export class SignHsp extends BaseSign {
  protected readonly inputFile: string | undefined;
  protected readonly outputFile: string | undefined;

  constructor(targetService: TargetTaskService) {
    super(targetService, TaskNames.CommonTask.SIGN_HSP);
    this.inputFile = path.resolve(
      this.pathInfo.getModuleBuildOutputPath(),
      this.targetData.getModuleTargetOutputFileName('', false, BuildArtifactExtension.DOT_HSP),
    );
    this.outputFile = path.resolve(
      this.pathInfo.getModuleBuildOutputPath(),
      this.targetData.getModuleTargetOutputFileName('', true, BuildArtifactExtension.DOT_HSP),
    );
  }

  declareInputFiles(): FileSet {
    return super.declareInputFiles().addEntry(this.inputFile!, { isDirectory: false });
  }

  declareOutputFiles(): FileSet {
    if (this.outputFile) {
      super.declareOutputFiles().addEntry(this.outputFile, { isDirectory: false });
    }
    return super.declareOutputFiles();
  }

  protected async doTaskAction() {
    const signModel = new SignModel(this.signType, this.inputFile!, this.outputFile!);

    // 当任务非增量时，先删除上一次已签名的输出文件
    FileUtil.deleteFile(signModel.getOutPutFilePath());
    if (!hvigorCore.getParameter().getProperty(CommonConst.ENABLE_SIGN_TASK)) {
      return;
    }
    await this.signUtil.sign(signModel, this.durationEvent);
  }

  initTaskDepends() {
    this.declareDepends(PackageHsp.name);
  }
}
